package Cliente.ventanas;

import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import Cliente.TCPCliente;

public class MainWindow extends JFrame implements ChangeListener{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	static TCPCliente tcpServer;
	int J = 0;
	JTabbedPane tab;
	ArrayList<String> listaTren;

	public MainWindow(TCPCliente tcp){
		
		tcpServer = tcp;
		listaTren=listTren();
		
//		JLayeredPane layer = new JLayeredPane();
		ButtonPanel button = new ButtonPanel(this, tcpServer);
		tab = new JTabbedPane();
		for(int j=0; j<listaTren.size();j++){
			InfoTrenPanel panel = new InfoTrenPanel(this, Integer.parseInt(listaTren.get(j)),tcpServer);
			tab.add(panel);
			panel.setBounds(0,100,500,400);
			tab.add("Tren "+Integer.parseInt(listaTren.get(j)), panel);
		}
		
		tab.addChangeListener(this);
		
		this.setSize(500,500);
		
		this.setVisible(true);
		this.setLayout(null);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		this.stateChanged(null);
//		layer.setLayout(null);
		
//		this.add(layer);

//		layer.setBounds(0, 0, 500, 400);
		

		this.add(button);
		this.add(tab);
		
		tab.setBounds(0, 100, 500, 400);

		button.setBounds(0,0,500,100);
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

	}
	
	public ArrayList<String> listTren(){
		ArrayList<String> list = new ArrayList<String>();
		try {
			tcpServer.sentMessage("LISTRAIN\n");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		do{
			try {
				String comandoRecibido=tcpServer.receiveMessage();
				list.add(comandoRecibido);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}while(!list.get(list.size()-1).contains("222 OK"));
//		System.out.println("Problema"+list.size());
		for(String s:list){
			System.out.println(s);
		}
		list.remove(list.size()-1);
		list.remove(0);

		return list;
		
	}

	public void actualizar(){
		try {
			InfoTrenPanel trenpan= (InfoTrenPanel)tab.getSelectedComponent();
//			System.out.println("trenpan....."+trenpan.getVehic());
			tcpServer.sentMessage("SWITCHTRAIN "+trenpan.getVehic()+"\n");
			String comando=tcpServer.receiveMessage();
			trenpan.actualizarVentana(trenpan.ObtenerSubString(comando, ';', 21), trenpan.ObtenerSubString(comando, ';', trenpan.getFin()+1), comando.substring(trenpan.getFin()+1, comando.length()));
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	@Override
	public void stateChanged(ChangeEvent e) {
		// TODO Auto-generated method stub
		actualizar();
	}

}
